<template>
  <div>
    <Header></Header>
    <curr-locat title="个人信息"></curr-locat>
    <div class="contain">
      <!-- 该功能还未添加，待完善 <div class="row">
        <div class="col-1">个人头像：</div>
        <div class="col-2">
          <img src="../../assets/image/musict.jpg" width="150" alt />
        </div>
      </div> -->
      <!-- <div class="row">
        <div class="col-1">密码：</div>
        <div class="col-2">{{ userinfo.password }}</div>
      </div> -->
      <el-row class="row" :gutter="24" type="flex" align="middle">
        <el-col :span="4" align="right">姓名：</el-col>
        <el-col :span="8">{{ userinfo.username }}</el-col>
      </el-row>
      <el-row class="row" :gutter="24" type="flex" align="middle">
        <el-col :span="4" align="right">邮箱：</el-col>
        <el-col :span="8">{{ userinfo.email }}</el-col>
      </el-row>
      <el-row class="row" :gutter="24" type="flex" align="middle">
        <el-col :span="4" align="right">联系电话：</el-col>
        <el-col :span="8">{{ userinfo.mobile }}</el-col>
      </el-row>
      <el-row class="row" :gutter="24" type="flex" align="middle">
        <el-col :span="4" align="right">操作：</el-col>
        <el-col :span="4">
          <el-button type="warning" @click="dialogFormVisible = true">修改个人信息</el-button>
          <!-- 修改个人信息弹框 -->
          <el-dialog title="修改个人信息" :visible.sync="dialogFormVisible" @close="addDialogClosed">
            <el-form :model="modifyPersonForm" :rules="modifyPersonRules" ref="modifyPersonFormRef">
              <el-form-item label="名称：" prop="username" :label-width="formLabelWidth">
                <el-input v-model="modifyPersonForm.username" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="邮箱：" prop="email" :label-width="formLabelWidth">
                <el-input v-model="modifyPersonForm.email" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="电话：" prop="mobile" :label-width="formLabelWidth">
                <el-input v-model="modifyPersonForm.mobile" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="modifyInfo">确 定</el-button>
            </div>
          </el-dialog>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogPassVisible = true">修改密码</el-button>
          <!-- 修改密码 -->
          <el-dialog title="修改密码" :visible.sync="dialogPassVisible" @close="resetForm">
            <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="旧密码：" prop="passOld">
                <el-input type="password" v-model="ruleForm.passOld" autocomplete="off" show-password></el-input>
              </el-form-item>
              <el-form-item label="新密码：" prop="pass">
                <el-input type="password" v-model="ruleForm.pass" autocomplete="off" show-password></el-input>
              </el-form-item>
              <el-form-item label="确定新密码：" prop="checkPass">
                <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off" show-password></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="resetForm">取 消</el-button>
              <el-button type="primary" @click="modifyPass('ruleForm')">确 定</el-button>
            </div>
          </el-dialog>
        </el-col>
      </el-row>
    </div>
    <Footer></Footer>
  </div>
</template>

<script>
import { getUserAllInfo, updateUserInfo, modifyPassWorldInfo } from '../../network/product';
export default {
  name: 'PersonInfo',
  data() {
    //  自定义校验 邮箱和手机号
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])/;
      if (regEmail.test(value)) {
        // 为 true 就是合法邮箱
        return cb();
      }
      cb(new Error('请输入合法的邮箱！'));
    };
    var checkPhone = (rule, value, cb) => {
      const regMobail = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobail.test(value)) {
        // 为 true 就是合法邮箱
        return cb();
      }
      cb(new Error('请输入合法的电话号码！'));
    };
    // 确认密码验证
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      dialogFormVisible: false,
      dialogPassVisible: false,
      // 用户信息显示
      userinfo: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改显示表单
      form: {
        username: '',
        email: '',
        phone: ''
      },
      formLabelWidth: '120px',
      // 修改提交表单
      modifyPersonForm: {
        id: '',
        userId: '',
        username: '',
        email: '',
        mobile: '',
        updateDate: '',
        updater: ''
      },
      modifyPersonRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [{ required: true, validator: checkPhone, trigger: 'blur' }]
      },
      // 输入表单
      ruleForm: {
        passOld: '',
        pass: '',
        checkPass: ''
      },
      // 提交参数
      isPass: {},
      // 验证规则
      rules: {
        passOld: [
          { validator: validatePass, trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码长度6到15个字符以内',
            trigger: 'blur'
          }
        ],
        pass: [
          { validator: validatePass, trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码长度6到15个字符以内',
            trigger: 'blur'
          }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码长度6到15个字符以内',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  mounted() {
    // 获取所有用户信息
    this.getUser();
  },
  methods: {
    // 获取所有用户信息
    getUser() {
      getUserAllInfo().then((res) => {
        if (res.data.code === 0) {
          res.data.rows.map((item) => {
            // 如果等于但前用户信息就添加
            if (item.username == localStorage.getItem('username')) {
              // 展示的用户信息
              this.userinfo = {
                username: item.username,
                password: item.password,
                email: item.email,
                mobile: item.mobile
              };
              this.modifyPersonForm = {
                id: item.id,
                userId: item.userId,
                username: item.username,
                email: item.email,
                mobile: item.mobile
              };
            }
          });
        } else {
          this.$message({
            showClose: true,
            message: '信息获取失败,请联系管理员！',
            type: 'error',
            duration: 4000
          });
        }
      });
    },
    // 修改用户信息
    modifyInfo() {
      this.$refs.modifyPersonFormRef.validate(async (valid) => {
        if (!valid) return;
        // 修改用户信息表单完善
        this.modifyPersonForm = {
          ...this.modifyPersonForm,
          updateDate: this.getCurrTime(),
          updater: localStorage.getItem('username')
        };
        let self = this;
        // 发送网络请求 和 刷新用户列表信息
        updateUserInfo(this.modifyPersonForm)
          .then((res) => {
            if (res.data.code === 0) {
              this.$message({
                showClose: true,
                message: '恭喜您，修改成功！',
                type: 'success',
                duration: 4000
              });
              self.userinfo = {
                username: self.modifyPersonForm.username,
                email: self.modifyPersonForm.email,
                mobile: self.modifyPersonForm.mobile
              };
            } else {
              this.$message({
                showClose: true,
                message: '个人信息修改失败,请联系管理员！',
                type: 'error',
                duration: 4000
              });
            }
          })
          .catch((e) => {
            console.log(e);
          });
        this.dialogFormVisible = false;
      });
    },
    // 关闭添加信息 对话框的选中
    addDialogClosed() {
      this.$refs.modifyPersonFormRef.resetFields();
    },
    /**
     * 获取当前时间
     * return time
     */
    getCurrTime() {
      let date = new Date(); //实例一个时间对象；
      let year = date.getFullYear(); //获取系统的年；
      let month = date.getMonth() + 1; //获取系统月份，由于月份是从0开始计算，所以要加1
      month = month < 10 ? '0' + month : month;
      let day = date.getDate(); //获取系统日
      day = day < 10 ? '0' + day : day;
      let hour = date.getHours(); //获取系统时间
      hour = hour < 10 ? '0' + hour : hour;
      let minute = date.getMinutes(); //分
      minute = minute < 10 ? '0' + minute : minute;
      let second = date.getSeconds(); //秒
      second = second < 10 ? '0' + second : second;
      let time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
      return time;
    },
    /**
     * 修改密码
     * @formName 修改密码 formRef
     */
    modifyPass(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isPass = {
            newPassword: this.ruleForm.pass,
            oldPassword: this.ruleForm.passOld
          };
          modifyPassWorldInfo(this.isPass).then((res) => {
            if (res.data.code === 0 && res.status === 200) {
              this.$message({
                showClose: true,
                message: '密码修改成功！请重新登录！',
                type: 'success',
                duration: 4000
              });
              this.$router.push('/main');
            } else {
              this.$message({
                showClose: true,
                message: '旧密码输入错误，请重新输入！',
                type: 'error',
                duration: 4000
              });
              return;
            }
          });
        } else {
          this.$message({
            showClose: true,
            message: '请输入密码！',
            type: 'warning',
            duration: 4000
          });
          return false;
        }
      });
    },
    resetForm() {
      this.dialogPassVisible = false;
      this.$refs.ruleForm.resetFields();
    }
  }
};
</script>

<style lang="less" scoped>
.row {
  border-bottom: 1px solid #a29a9a;
  color: #333;
  font-size: 16px;
  padding: 10px 0;
}
</style>
